<template>
  <div class="commission-rates-page">
    <!-- 页面标题和操作按钮 -->
    <div class="page-header">
      <h2 class="page-title">分销比例管理</h2>
      <div class="header-actions">
        <button @click="handleAddConfig" class="action-btn primary">
          <svg viewBox="0 0 24 24" class="btn-icon">
            <path d="M19,13H13V19H11V13H5V11H11V5H13V11H19V13Z"/>
          </svg>
          新增配置
        </button>
      </div>
    </div>

    <!-- 筛选表单 -->
    <div class="filter-container">
      <div class="filter-form">
        <div class="form-group">
          <label>门店</label>
          <select v-model="queryParams.storeId" @change="handleSearch" class="filter-select">
            <option value="">全部</option>
            <option value="0">全局配置</option>
            <option v-for="store in storeOptions" :key="store.id" :value="store.id">
              {{ store.name }}
            </option>
          </select>
        </div>
        <div class="form-actions">
          <button @click="handleSearch" class="action-btn primary">查询</button>
          <button @click="resetQuery" class="action-btn">重置</button>
        </div>
      </div>
    </div>

    <!-- 数据表格 -->
    <div class="data-card">
      <div class="data-table" :class="{ 'loading': loading }">
        <div class="table-header">
          <div class="header-cell cell-id">ID</div>
          <div class="header-cell cell-store">门店</div>
          <div class="header-cell cell-level">分销等级</div>
          <div class="header-cell cell-rate">佣金比例</div>
          <div class="header-cell cell-status">状态</div>
          <div class="header-cell cell-desc">说明</div>
          <div class="header-cell cell-creator">创建人</div>
          <div class="header-cell cell-action">操作</div>
        </div>
        
        <div class="table-body">
          <div v-if="configList.length === 0 && !loading" class="empty-data">
            <div class="empty-icon">
              <svg viewBox="0 0 24 24">
                <path d="M3 17.25V21H6.75L17.81 9.94L14.06 6.19L3 17.25M22.61 18.36L18.36 22.61L13.16 17.41L14.06 16.5L15.47 17.93L17.31 16.09L18.75 17.5L17.91 18.36L19.33 19.78L20.2 18.92L21.58 20.3L22.61 19.27L21.3 18L22.61 16.72L21.12 15.22L19.3 17.04L17.91 15.64L19.73 13.81L18.36 12.45L17.06 13.75L15.54 12.25L16.35 11.44L15.7 10.81L20.91 16.09L22.61 14.39L24 15.75L22.61 17.12L24 18.5L22.61 19.87L21.12 18.38L22.61 16.9L22.61 18.36M12.45 11L14.06 9.39L16.67 12L15.06 13.61L12.45 11Z"/>
              </svg>
            </div>
            <p>暂无佣金配置数据</p>
          </div>
          
          <div v-for="item in configList" :key="item.id" class="table-row">
            <div class="table-cell cell-id">{{ item.id }}</div>
            <div class="table-cell cell-store">
              <span class="store-tag" v-if="item.storeId === 0">全局配置</span>
              <span v-else>{{ item.storeName }}</span>
            </div>
            <div class="table-cell cell-level">
              <span class="level-badge" :class="'level' + item.level">
                {{ getLevelText(item.level) }}
              </span>
            </div>
            <div class="table-cell cell-rate">
              {{ (item.commissionRate * 100).toFixed(2) + '%' }}
            </div>
            <div class="table-cell cell-status">
              <div class="toggle-switch">
                <input 
                  type="checkbox" 
                  :id="'switch-' + item.id" 
                  :checked="item.isActive === 1"
                  @change="handleStatusChange(item)"
                >
                <label :for="'switch-' + item.id"></label>
              </div>
            </div>
            <div class="table-cell cell-desc">{{ item.description }}</div>
            <div class="table-cell cell-creator">{{ item.creatorName }}</div>
            <div class="table-cell cell-action">
              <div class="action-buttons">
                <button @click="handleEdit(item)" class="action-btn edit">编辑</button>
                <button @click="handleDelete(item)" class="action-btn delete">删除</button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination">
        <button class="page-btn" :disabled="queryParams.page <= 1" @click="handlePrevPage">&lt;</button>
        <button 
          v-for="page in getPageNumbers()" 
          :key="page" 
          class="page-btn" 
          :class="{ active: queryParams.page === page }"
          @click="handlePageClick(page)"
        >
          {{ page }}
        </button>
        <button class="page-btn" :disabled="queryParams.page >= getPageCount()" @click="handleNextPage">&gt;</button>
      </div>
    </div>

    <!-- 表单弹窗 -->
    <div class="modal" v-if="dialogVisible">
      <div class="modal-overlay" @click="dialogVisible = false"></div>
      <div class="modal-container">
        <div class="modal-header">
          <h3>{{ formTitle }}</h3>
          <button @click="dialogVisible = false" class="close-btn">
            <svg viewBox="0 0 24 24">
              <path d="M19,6.41L17.59,5L12,10.59L6.41,5L5,6.41L10.59,12L5,17.59L6.41,19L12,13.41L17.59,19L19,17.59L13.41,12L19,6.41Z"/>
            </svg>
          </button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="submitForm" ref="formRef" class="form">
            <div class="form-group">
              <label>门店</label>
              <select v-model="formData.storeId" required class="form-select">
                <option value="0">全局配置</option>
                <option v-for="store in storeOptions" :key="store.id" :value="store.id">
                  {{ store.name }}
                </option>
              </select>
            </div>
            <div class="form-group">
              <label>分销等级</label>
              <select v-model="formData.level" required class="form-select">
                <option :value="1">一级分销员</option>
                <option :value="2">二级分销员</option>
                <option :value="3">三级分销员</option>
              </select>
            </div>
            <div class="form-group">
              <label>佣金比例</label>
              <input 
                type="number" 
                v-model="formData.commissionRate" 
                min="0" 
                max="1" 
                step="0.01" 
                required 
                class="form-input"
              >
              <div class="form-tip">佣金比例为0-1之间的小数，如0.1表示10%</div>
            </div>
            <div class="form-group">
              <label>状态</label>
              <div class="toggle-switch form-switch">
                <input 
                  type="checkbox" 
                  id="form-switch" 
                  v-model="formActiveValue"
                >
                <label for="form-switch"></label>
                <span>{{ formActiveValue ? '启用' : '停用' }}</span>
              </div>
            </div>
            <div class="form-group">
              <label>说明</label>
              <textarea 
                v-model="formData.description" 
                placeholder="请输入配置说明"
                class="form-textarea"
                rows="3"
              ></textarea>
            </div>
          </form>
        </div>
        <div class="modal-footer">
          <button @click="dialogVisible = false" class="action-btn">取消</button>
          <button @click="submitForm" class="action-btn primary">确定</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { 
  getCommissionConfigList, 
  getCommissionConfigById, 
  addCommissionConfig, 
  updateCommissionConfig, 
  deleteCommissionConfig 
} from '../../api/commission'
import { getStoreList } from '../../api/store'

// 状态定义
const loading = ref(false)
const dialogVisible = ref(false)
const formRef = ref(null)
const configList = ref([])
const total = ref(0)
const storeOptions = ref([])
const formActiveValue = ref(true)

// 查询参数
const queryParams = reactive({
  page: 1,
  size: 10,
  storeId: ''
})

// 表单数据
const formData = reactive({
  id: null,
  storeId: 0,
  level: 1,
  commissionRate: 0.1,
  isActive: 1,
  description: '',
  createdBy: null
})

// 计算属性
const formTitle = computed(() => {
  return formData.id ? '编辑佣金配置' : '新增佣金配置'
})

// 工具方法
const getLevelText = (level) => {
  switch(level) {
    case 1: return '一级分销员'
    case 2: return '二级分销员'
    case 3: return '三级分销员'
    default: return `${level}级分销员`
  }
}

const getPageCount = () => {
  return Math.ceil(total.value / queryParams.size)
}

const getPageNumbers = () => {
  const pageCount = getPageCount()
  const currentPage = queryParams.page
  
  // 最多显示5个页码
  if (pageCount <= 5) {
    return Array.from({ length: pageCount }, (_, i) => i + 1)
  }
  
  // 当前页在前3页
  if (currentPage <= 3) {
    return [1, 2, 3, 4, 5]
  }
  
  // 当前页在后3页
  if (currentPage >= pageCount - 2) {
    return [pageCount - 4, pageCount - 3, pageCount - 2, pageCount - 1, pageCount]
  }
  
  // 当前页在中间
  return [currentPage - 2, currentPage - 1, currentPage, currentPage + 1, currentPage + 2]
}

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    const res = await getCommissionConfigList({
      ...queryParams,
      storeId: queryParams.storeId === '' ? null : queryParams.storeId
    })
    configList.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    console.error('加载佣金配置失败:', error)
    alert('加载佣金配置失败')
  } finally {
    loading.value = false
  }
}

// 加载门店列表
const loadStores = async () => {
  try {
    const res = await getStoreList({ page: 1, size: 100 })
    storeOptions.value = res.data.list
  } catch (error) {
    console.error('加载门店列表失败:', error)
    alert('加载门店列表失败')
  }
}

// 查询
const handleSearch = () => {
  queryParams.page = 1
  loadData()
}

// 重置查询
const resetQuery = () => {
  queryParams.storeId = ''
  queryParams.page = 1
  loadData()
}

// 分页处理
const handlePrevPage = () => {
  if (queryParams.page > 1) {
    queryParams.page--
    loadData()
  }
}

const handleNextPage = () => {
  if (queryParams.page < getPageCount()) {
    queryParams.page++
    loadData()
  }
}

const handlePageClick = (page) => {
  queryParams.page = page
  loadData()
}

// 新增配置
const handleAddConfig = () => {
  resetForm()
  formData.createdBy = JSON.parse(localStorage.getItem('admin_info'))?.id || 1
  formActiveValue.value = true
  dialogVisible.value = true
}

// 编辑配置
const handleEdit = async (row) => {
  resetForm()
  formData.id = row.id
  
  try {
    const res = await getCommissionConfigById(row.id)
    Object.assign(formData, res.data)
    formActiveValue.value = formData.isActive === 1
    dialogVisible.value = true
  } catch (error) {
    console.error('获取配置详情失败:', error)
    alert('获取配置详情失败')
  }
}

// 删除配置
const handleDelete = (row) => {
  if (confirm('确定要删除该佣金配置吗？')) {
    deleteCommissionConfig(row.id)
      .then(() => {
        alert('删除成功')
        loadData()
      })
      .catch(error => {
        console.error('删除失败:', error)
        alert('删除失败: ' + (error.message || '未知错误'))
      })
  }
}

// 状态变更
const handleStatusChange = async (row) => {
  const newStatus = row.isActive === 1 ? 0 : 1
  try {
    await updateCommissionConfig(row.id, { isActive: newStatus })
    row.isActive = newStatus
    alert('状态更新成功')
  } catch (error) {
    console.error('状态更新失败:', error)
    alert('状态更新失败')
  }
}

// 重置表单
const resetForm = () => {
  formData.id = null
  formData.storeId = 0
  formData.level = 1
  formData.commissionRate = 0.1
  formData.isActive = 1
  formData.description = ''
}

// 提交表单
const submitForm = async () => {
  formData.isActive = formActiveValue.value ? 1 : 0
  
  try {
    if (formData.id) {
      // 更新
      await updateCommissionConfig(formData.id, formData)
      alert('更新佣金配置成功')
    } else {
      // 新增
      await addCommissionConfig(formData)
      alert('新增佣金配置成功')
    }
    
    dialogVisible.value = false
    loadData()
  } catch (error) {
    console.error('表单提交失败:', error)
    alert('表单提交失败: ' + (error.message || '未知错误'))
  }
}

onMounted(() => {
  loadData()
  loadStores()
})
</script>

<style scoped>
.commission-rates-page {
  max-width: 1400px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.page-title {
  font-size: 1.8rem;
  font-weight: 600;
  margin: 0;
  color: #2d3748;
}

.header-actions {
  display: flex;
  gap: 15px;
}

.action-btn {
  padding: 8px 16px;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  font-size: 0.9rem;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  background: white;
  transition: all 0.2s;
}

.action-btn:hover {
  border-color: #cbd5e0;
  background: #f8fafc;
}

.action-btn.primary {
  background: #5856d6;
  color: white;
  border-color: #5856d6;
}

.action-btn.primary:hover {
  background: #4644c8;
}

.action-btn.edit {
  color: #3182ce;
  border-color: #bee3f8;
}

.action-btn.edit:hover {
  background: #ebf8ff;
}

.action-btn.delete {
  color: #e53e3e;
  border-color: #fed7d7;
}

.action-btn.delete:hover {
  background: #fff5f5;
}

.btn-icon {
  width: 18px;
  height: 18px;
  fill: currentColor;
}

.filter-container {
  background: white;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  border: 1px solid #e2e8f0;
}

.filter-form {
  display: flex;
  align-items: center;
  gap: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
  min-width: 200px;
}

.form-group label {
  font-size: 0.9rem;
  font-weight: 500;
  color: #4a5568;
}

.filter-select, .form-select, .form-input, .form-textarea {
  padding: 10px 15px;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  font-size: 0.9rem;
  outline: none;
  transition: border-color 0.2s;
}

.filter-select:focus, .form-select:focus, .form-input:focus, .form-textarea:focus {
  border-color: #5856d6;
}

.form-actions {
  display: flex;
  gap: 10px;
  align-items: center;
  margin-left: auto;
}

.data-card {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  border: 1px solid #e2e8f0;
}

.data-table.loading {
  opacity: 0.6;
  pointer-events: none;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  overflow: hidden;
}

.table-header {
  display: grid;
  grid-template-columns: 80px 120px 140px 120px 100px 1fr 120px 160px;
  background: #f8fafc;
  border-bottom: 1px solid #e2e8f0;
  font-weight: 600;
}

.table-row {
  display: grid;
  grid-template-columns: 80px 120px 140px 120px 100px 1fr 120px 160px;
  border-bottom: 1px solid #f1f5f9;
  transition: background-color 0.2s;
}

.table-cell, .header-cell {
  padding: 15px 16px;
  display: flex;
  align-items: center;
  font-size: 0.9rem;
  overflow: hidden;
  text-overflow: ellipsis;
}

.cell-id {
  justify-content: center;
}

.cell-store {
  justify-content: flex-start;
}

.cell-level {
  justify-content: flex-start;
}

.cell-rate {
  justify-content: center;
}

.cell-status {
  justify-content: center;
}

.cell-desc {
  justify-content: flex-start;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.cell-creator {
  justify-content: center;
}

.cell-action {
  justify-content: center;
}

.table-row:hover {
  background: #f8fafc;
}

.table-row:last-child {
  border-bottom: none;
}

.header-cell {
  font-weight: 600;
  color: #4a5568;
}

.store-tag {
  background: #e2e8f0;
  color: #4a5568;
  padding: 4px 8px;
  border-radius: 6px;
  font-size: 0.8rem;
  white-space: nowrap;
}

.level-badge {
  padding: 4px 10px;
  border-radius: 6px;
  font-size: 0.8rem;
  font-weight: 500;
}

.level-badge.level1 {
  background: #c6f6d5;
  color: #276749;
}

.level-badge.level2 {
  background: #fefcbf;
  color: #975a16;
}

.level-badge.level3 {
  background: #e2e8f0;
  color: #4a5568;
}

.toggle-switch {
  position: relative;
  display: inline-block;
}

.toggle-switch input {
  opacity: 0;
  width: 0;
  height: 0;
}

.toggle-switch label {
  position: relative;
  display: inline-block;
  width: 48px;
  height: 24px;
  background-color: #cbd5e0;
  border-radius: 12px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.toggle-switch label:after {
  content: "";
  position: absolute;
  top: 2px;
  left: 2px;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background: white;
  transition: all 0.3s;
}

.toggle-switch input:checked + label {
  background-color: #5856d6;
}

.toggle-switch input:checked + label:after {
  transform: translateX(24px);
}

.form-switch {
  display: flex;
  align-items: center;
  gap: 10px;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.pagination {
  display: flex;
  justify-content: center;
  padding: 20px;
  gap: 8px;
}

.page-btn {
  width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid #e2e8f0;
  background: white;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s;
}

.page-btn:hover:not(:disabled) {
  border-color: #5856d6;
  color: #5856d6;
}

.page-btn.active {
  background: #5856d6;
  color: white;
  border-color: #5856d6;
}

.page-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 100;
}

.modal-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
}

.modal-container {
  position: relative;
  width: 500px;
  max-width: 90%;
  background: white;
  border-radius: 12px;
  box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
  overflow: hidden;
  display: flex;
  flex-direction: column;
  max-height: 90vh;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #e2e8f0;
}

.modal-header h3 {
  margin: 0;
  font-size: 1.25rem;
  color: #2d3748;
}

.close-btn {
  background: transparent;
  border: none;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  border-radius: 50%;
  transition: background-color 0.2s;
}

.close-btn:hover {
  background: #f1f5f9;
}

.close-btn svg {
  width: 20px;
  height: 20px;
  fill: #4a5568;
}

.modal-body {
  padding: 20px;
  overflow-y: auto;
}

.form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-tip {
  font-size: 12px;
  color: #718096;
  margin-top: 4px;
}

.modal-footer {
  padding: 15px 20px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  border-top: 1px solid #e2e8f0;
}

/* 适配小屏幕 */
@media screen and (max-width: 1280px) {
  .table-header,
  .table-row {
    grid-template-columns: 60px 110px 130px 100px 90px 1fr 100px 150px;
  }
  
  .table-cell, .header-cell {
    padding: 12px 10px;
    font-size: 0.85rem;
  }
}
</style> 